package com.example.mymap;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private MapView mMapView = null;
    private BaiduMap mBaiduMap = null;//定位图层
    private LocationClient mLocationClient = null;
    // 当前定位模式
    private MyLocationConfiguration.LocationMode locationMode;
    //是否是第一次定位
    private boolean isFirstLocate = true;
    //当前定位模式
    private MyLocationConfiguration.LocationMode mLocationMode;
    private static final int BAIDU_READ_PHONE_STATE =100;
    //声明文本框
    private TextView library_des, tech_des, dining_des = null;
    //地点信息
    private Place_Info tech_info = new Place_Info(R.string.tech_name, R.string.tech_des, R.drawable.pic_tech);
    private Place_Info library_info = new Place_Info(R.string.library_name, R.string.library_des, R.drawable.pic_library);
    private Place_Info dining_info = new Place_Info(R.string.dining_name, R.string.dining_des, R.drawable.pic_dining);
    //消息传递
    private Intent mIntent = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化地图必须放在布局初始化之前
        //地图初始化方法中任选一种
        SDKInitializer.initialize(getApplicationContext());

        setContentView(R.layout.activity_main);

        //获取定位权限后初始化
        showContacts();

    }

    private void init(){
        //获取地图控件
        mMapView = findViewById(R.id.themapView);
        //得到地图
        mBaiduMap = mMapView.getMap();

        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        //绑定按钮监听事件
        findViewById(R.id.btn_library).setOnClickListener(this);
        findViewById(R.id.btn_tech).setOnClickListener(this);
        findViewById(R.id.btn_dining).setOnClickListener(this);

        //设置地图标点
        //创建OverlayOptions的集合
        List<OverlayOptions> options = new ArrayList<OverlayOptions>();
        //构造坐标数据
        //经纬度可以通过百度地图官网进行搜索获得
        LatLng p_library = new LatLng(36.674945, 117.144168);
        LatLng p_teach = new LatLng(36.673717, 117.145928);
        LatLng p_dining = new LatLng(36.672553, 117.147145);

        //自定义Marker的图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_mark);
        //创建OverlayOptions属性
        OverlayOptions option1 =  new MarkerOptions()
                .position(p_library)
                .icon(bitmap);
        OverlayOptions option2 =  new MarkerOptions()
                .position(p_teach)
                .icon(bitmap);
        OverlayOptions option3 =  new MarkerOptions()
                .position(p_dining)
                .icon(bitmap);
        //将OverlayOptions添加到list
        options.add(option1);
        options.add(option2);
        options.add(option3);

        //设置mark覆盖物点击监听器
       // mBaiduMap.setOnMarkerClickListener(new MyMarkerClickListener());
        //在地图上批量添加
        mBaiduMap.addOverlays(options);

        //定位初始化
        mLocationClient = new LocationClient(this);

        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(5000);//五秒返回一次位置
        // 可选，设置地址信息
        option.setIsNeedAddress(true);
        //可选，设置是否需要地址描述
        option.setIsNeedLocationDescribe(true);

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();
        //如果要改为FOLLOWING模式
        //locationMode = MyLocationConfiguration.LocationMode.FOLLOWING;
        // 定位模式、是否开启方向、设置自定义定位图标、精度圈填充颜色以及精度圈边框颜色5个属性（此处只设置了前三个）。
        //MyLocationConfiguration mLocationConfiguration = new MyLocationConfiguration(locationMode,true,null);
        // 使自定义的配置生效
        //mBaiduMap.setMyLocationConfiguration(mLocationConfiguration);

    }

    //重写onReceieveLocation方法获取定位数据，并传给mapview
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null){
                return;
            }

            // 如果是第一次定位
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            if (isFirstLocate) {
                isFirstLocate = false;
                //给地图设置状态
                MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(update);
                update = MapStatusUpdateFactory.zoomTo(18f);
                mBaiduMap.animateMapStatus(update);
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
        }
    }



    //按钮点击监听器
    @Override
    public void onClick(View v){
        if(v.getId() == R.id.btn_library){
            mIntent = new Intent(MainActivity.this, DescriptionActivity.class);
            //使用Bundle来传递Int类型的数据
            Bundle bundle = new Bundle();
            bundle.putInt("name", library_info.getName());
            bundle.putInt("des",library_info.getDescreption());
            bundle.putInt("picname", library_info.getPicname());
            mIntent.putExtras(bundle);
            startActivity(mIntent);
        }else if(v.getId() == R.id.btn_tech){
            mIntent = new Intent(MainActivity.this, DescriptionActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("name", tech_info.getName());
            bundle.putInt("des",tech_info.getDescreption());
            bundle.putInt("picname", tech_info.getPicname());
            mIntent.putExtras(bundle);
            startActivity(mIntent);
        }else if(v.getId() == R.id.btn_dining){
            mIntent = new Intent(MainActivity.this, DescriptionActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("name", dining_info.getName());
            bundle.putInt("des",dining_info.getDescreption());
            bundle.putInt("picname", dining_info.getPicname());
            mIntent.putExtras(bundle);
            startActivity(mIntent);
        }

    }

    //申请权限
    public void showContacts(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
             //Toast.makeText(getApplicationContext(),"没有权限,请手动开启定位权限",Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, BAIDU_READ_PHONE_STATE);
        }else{
            init();
        }
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    init();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    //实现地图生命周期管理
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

}